using System;
using System.Collections.Generic;
using System.Text;
using Zoo;
using System.Diagnostics;
using SubSonic;
using System.IO;
using System.Web;


namespace Zoo
{

    public partial class RegisterController
    {
        private IRegisterView _registerView;
        private IZooModel _zooModel;
        private Dictionary _dictionary;
        private const int MAX_SIZE_FILE_UPLOAD = 2100000;

        public RegisterController(IRegisterView registerView,IZooModel zooModel)
        {
            _registerView = registerView;
            _zooModel = zooModel;
            _dictionary = Dictionary.CreateFromCache(_registerView.Language,zooModel);

            //PostCondition
            Debug.Assert(_dictionary != null, "Dictionary is Null!");
            Debug.Assert(_zooModel != null, "Model is null!");
            Debug.Assert(_registerView != null, "RegisterView is null!"); 

            
        }

        public void Initialize()
        {
            
            _registerView.Subscribe+=new EventHandler(Subscribe);

            if (!_registerView.IsPostBack)
            {
                initDateControls();
                _registerView.LanguageValues = _dictionary.GetListItemValues("LanguageValues");
                _registerView.GenderValues = _dictionary.GetListItemValues("GenderValues");
                _registerView.SeekingValues = _dictionary.GetListItemValues("GenderValues");
   
                _registerView.UserLanguage = _registerView.Language;
                _registerView.Gender = "m";
                _registerView.Seeking = "f";
            }
            //PostConditions
            Debug.Assert(_registerView.LanguageValues != null, "RegisterView Languagevalues should not be null!");
            Debug.Assert(_registerView.GenderValues != null, "RegisterView Gendervalues should not be null");
            Debug.Assert(_registerView.SeekingValues != null, "RegisterView SeekingValues should not be null!");

          
        }

        public void  Subscribe(object sender, EventArgs e)
        {

            if (validateForm(_registerView))
            {
                
                DateTime bornDate=DateTime.Parse(Utility.GetDateString(_registerView.BornDateDay,_registerView.BornDateMonth,_registerView.BornDateYear));

                IPictureStorage pictureStorage = PictureStorageFactory.CreatePictureStorage();

                try
                {
                    _zooModel.Register(
                        _registerView.UserLanguage,
                        _registerView.NickName,
                        _registerView.EmailAddress,
                        _registerView.Gender,
                        _registerView.Seeking,
                        _registerView.CountryID,
                        _registerView.RegionID,
                        bornDate,
                        _registerView.City,
                        _registerView.Description,
                        _registerView.Password,
                        _registerView.EmailOptin,
                        _registerView.FileContent,
                        pictureStorage
                        );
                    
                    _registerView.GoTo("Confirm.aspx");
                }
                catch (InvalidImageException)
                {
                    Trace.TraceError("Invalid image was uploaded!");
                    _registerView.ErrorMessage += _dictionary["Register_InvalidImageException"];
                }
            }
 	        
        }

        private void initDateControls()
        {
            for (int day = 1; day <= 31; day++)
            {
                _registerView.DayValues.Add(day.ToString());
            }

            for (int month = 1; month <= 12; month++)
            {
                _registerView.MonthValues.Add(month.ToString());
            }

            for (int year = DateTime.Now.Year; year >= 1910; year--)
            {
                _registerView.YearValues.Add(year.ToString());
            }
        }

        private bool validateForm(IRegisterView _registerView)
        {
            _registerView.ErrorMessage = String.Empty;
            DateTime bornDate;
            string dateString = Utility.GetDateString(_registerView.BornDateDay, _registerView.BornDateMonth, _registerView.BornDateYear);

            if (!DateTime.TryParse(dateString, out bornDate))
                _registerView.ErrorMessage += _dictionary["ValidationError_InvalidDateTime"] + "<br/>";

            if (Utility.IsEmpty(_registerView.City)
                || _registerView.BornDateDay < 1
                || _registerView.BornDateMonth < 1
                || _registerView.BornDateYear < 1
                || Utility.IsEmpty(_registerView.CountryID.ToString())
                || Utility.IsEmpty(_registerView.Description)
                || Utility.IsEmpty(_registerView.EmailAddress)
                || Utility.IsEmpty(_registerView.Gender)
                || Utility.IsEmpty(_registerView.NickName)
                || _registerView.RegionID< 1
                || _registerView.CountryID < 1
                || Utility.IsEmpty(_registerView.Seeking)
                || Utility.IsEmpty(_registerView.UserLanguage)
                )
                _registerView.ErrorMessage += _dictionary["ValidationError_MandatoryFieldMissing"] + "<br/>";

            if (_zooModel.UserExist(_registerView.NickName))
                _registerView.ErrorMessage += _dictionary["ValidationError_NickNameAllreadyInUse"] + "<br/>";

            if (!_registerView.HasFile)
                _registerView.ErrorMessage += _dictionary["ValidationError_NoPicture"] + "<br/>";

            if (_registerView.HasFile && _registerView.FileContent.Length > MAX_SIZE_FILE_UPLOAD)
                _registerView.ErrorMessage += _dictionary["ValidationError_PictureToBig"] + "<br/>";

            return _registerView.ErrorMessage.Length == 0;

        }
    }
}